const express = require('express');
const router = express.Router();
const request = require('request');

const config = require('config');
// const myAxios = require('../../lib/myAxios');
// const BS = require('../../lib/serverBase2');

var wsMap = new Map();
var noWsMap = new Map();
var orderIdMap = new Map();
console.log('start');
router.ws('/',function (ws, req) {
    // ws = ws.ws;
    // req = req.req;

    //没有订单号
    if (!req.query.orderSn) {
		return;
    }

	let orderSn =  String(req.query.orderSn);
    console.log('orderSn '+orderSn);

    // /*根据订单号存储连接*/
	wsMap.set(orderSn, ws);

	try {
        ws.send('ok');
	} catch (err) {
		console.error(err);
	}
	console.log('[GJJ ws] 连接数' + wsMap.size);

	/*接收信息*/
	ws.on('message', function (msg) {

        // if (msg.indexOf('name' > -1)) {
        //     msg = JSON.parse(msg);
        //     if (orderIdMap.has(String(req.query.taskId))) {
        //         orderIdMap.get(String(req.query.taskId)).needGeneral = 1;
        //         orderIdMap.get(String(req.query.taskId)).name = msg.name;
        //         orderIdMap.get(String(req.query.taskId)).ID = msg.ID;
        //         orderIdMap.get(String(req.query.taskId)).phone = msg.phone;
        //         console.log(orderIdMap.get(String(req.query.taskId)));
        //     }
        // }
        console.log(msg);
	});

	/*断开连接*/
	ws.on('close', function () {
		if (wsMap.has(orderSn)) {
			wsMap.delete(orderSn);
			console.log('[GJJ]ws连接断开');
		}
	});
});

/**
 * ws结果通知
 */
router.post('/notify', function (req, res) {

	console.log('[ws/notify] ', JSON.stringify(req.body));

	if(req.body.orderSn && req.body.data){

        let orderSn = String(req.body.orderSn);//订单号
        let data = DataTransation(req.body.data);//响应数据

        let item = 10;

        if(wsMap.get(orderSn)){
            wsSendBack(orderSn, data);
        }else{
            let trmy = setInterval(function(){
                item--;
                if(wsMap.get(orderSn)){
                    clearInterval(trmy);
                    wsSendBack(orderSn, data);
                }else if(item<0){
                    console.error('[ws/notify] 连接丢失或没有找到 orderSn='+orderSn);
                    clearInterval(trmy);
                }
            },1000);
        }

        // console.log('[phpws/result] orderSn='+orderSn+' notifyData='+JSON.stringify(data));
        res.send({"state":0,"msg":"ok"});

    }else{
        res.send({"state":-1,"msg":"fail order or data"});
    }

});

/**
 * ws通知前端
 */
router.post('/NotifyCli', function (req,res){

    try{
        console.log('[ws/NotifyCli] ', JSON.stringify(req.body));
        if(!req.body.orderSn){
            throw "empty orderSn";
        }
        if(!req.body.data.returnUrl){
            throw "empty returnUrl";
        }


        if(req.body.code==0 && req.body.data && req.body.data.returnUrl){
            let orderSn = String(req.body.orderSn);//订单号
            let data = req.body.data;//响应数据
            // let returnUrl = data.returnUrl;

            //等待10秒
            let item = 10;
            if(wsMap.get(orderSn)){
                //console.log('[ws/notifyCli] success '+orderSn);
                wsSendBack(orderSn, data);
            }else{
                //等待核心
                let myVar = setInterval(function(){
                    //console.log('[ws/notifyCli]loading....'+orderSn);
                    item--;
                    if(wsMap.get(orderSn)){
                        clearInterval(myVar);
                        wsSendBack(orderSn, data);
                    }else if(item<0){
                        clearInterval(myVar);
                    }
                },1000);
            }
            res.send({"state":0,"msg":"ok"});//响应
        }else{
            throw "连接失败，发送失败";
        }
    }catch(err){
        console.error(err);
        res.send({"state":-1,"msg":err});
    }

});

/**
 * 根据orderSn发送通知
 * @param orderSn
 * @param data
 */
function wsSendBack(orderSn, data) {
    if(wsMap.get(orderSn)){
        wsMap.get(orderSn).send(JSON.stringify(data));//发送
    }else{
        console.error('[phpws/result] Link loss (没有找到长连接) orderSn='+orderSn);
    }
}

/**
 * 通知数据格式转换
 * @param data
 * @returns {{}}
 * @constructor
 */
function DataTransation(data){
    let outData = {};

    let temple = {
        "task_status":"status"
    }

    let loginTemple = {
        "phoneCode":"手机验证码"
    }

    for(x in data){
        if(temple[x]){
            outData[temple[x]] = data[x];
        }else{
            outData[x] = data[x];
        }
    }
    if(outData.status && outData.status==4){
        if(outData.fetch_res){
            let fetch_res = JSON.parse(outData.fetch_res);
            if(fetch_res.data.loginParam){
                outData.loginParam = fetch_res.data.loginParam;
                for(i in outData.loginParam){
                    if(loginTemple[outData.loginParam[i].name]){
                        outData.loginParam[i].note = loginTemple[outData.loginParam[i].name];
                    }else{
                        console.error('loginParam '+outData.loginParam[i].name);
                        outData.loginParam[i].note = outData.loginParam[i].name;
                    }
                }
            }
        }
    }

    return outData;
}


setInterval(function () {
	let dateNow = new Date().getTime();
	console.log('[dealBeforeSize： ]' + orderIdMap.size + ' loopMap:' + noWsMap.size);
	orderIdMap.forEach(function (value, key) {
		if (dateNow - value.addTime > 1000 * 60 * 30) {
			orderIdMap.delete(key);
		}
	});
	noWsMap.forEach(function (value, key) {
		if (dateNow - value.addTime > 1000 * 60 * 30) {
			noWsMap.delete(key);
		}
	});

	console.log('[dealAfterSize： ]' + orderIdMap.size + ' loopMap:' + noWsMap.size);
}, 1000 * 60 * 30);

module.exports = router;
